import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { Form, Button, Space, InputNumber } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import Checkbox from 'antd/lib/checkbox/Checkbox';
import type { Rules } from './index.d';
import './index.css';

interface Props extends AnyVal {
  dataSource?: Rules[];
  preContent: any;
  afterHalfContent: any;
  onChange?: (data: any) => void;
}


const DEFAULT_RULE: Rules = {
  start: undefined,
  end: undefined,
  reward: undefined,
  infinity: false,
}


const BaseDynamicRule: React.FC<Props> = (props) => {
  const { dataSource = [DEFAULT_RULE], preContent, afterHalfContent, onChange } = props;
  const [form] = Form.useForm();
  const addBtn: any = useRef(null);

  useEffect(() => {
    form.setFieldsValue({ rules: dataSource })
  }, [form, dataSource]);

  /**
   * @returns boolean 是否存在’无上限‘
   */
  const hasInfinity = useCallback(() => {
    const rules = form.getFieldsValue()?.rules ?? [];
    return rules.findIndex((v: Rules) => v?.infinity);
  }, [form]);

  /**
   * 验证通过-->>callback
   */
  const onFinish = useCallback(() => {
    form.validateFields().then(values => {
      console.log('Received values of form:', values);
      if (onChange) onChange(values);
    }).catch(err => {
      console.log('errr', err)
    })
  }, [form, onChange]);

  /**
   * 选择“无限制”操作
   */
  const checkItem = useCallback((index: number) => {
    const formVal: Rules[] = [...form.getFieldsValue().rules];
    if (!formVal[index]) {
      formVal[index] = DEFAULT_RULE;
    }
    if (formVal[index]?.infinity) {
      formVal[index].infinity = false
    } else {
      formVal[index].infinity = true;
      formVal[index].end = undefined;
    }
    form.setFieldsValue({ rules: formVal });
  }, [form]);

  const DynamicFormList = useMemo(() => (
    <Form.List name="rules">
      {(fields, fn) => {
        const { add, remove } = fn;
        return (
          <>
            {console.log('re')
            }
            {fields.map((field) => {
              const { key, name, fieldKey, ...rest } = field;
              const currentRule = form.getFieldsValue()?.rules[name] ?? {};
              return (
                <Space key={name} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                  {preContent?.label}<Form.Item
                    {...rest}
                    name={[name, 'start']}
                    fieldKey={[fieldKey, 'start']}
                    rules={[{ required: true, message: preContent?.placeholder }]}
                  >
                    <InputNumber min={0} placeholder={preContent?.placeholder} />
                  </Form.Item>
                  {preContent?.unit}
                至
                  <Form.Item
                    {...rest}
                    name={[name, 'end']}
                    fieldKey={[fieldKey, 'end']}
                    rules={[{
                      required: !currentRule?.infinity,
                      message: preContent?.placeholder,
                    }]}
                  >
                    <InputNumber min={currentRule?.start ? currentRule?.start : 0} placeholder={currentRule?.infinity ? '' : preContent?.placeholder} disabled={currentRule?.infinity} />
                  </Form.Item>
                  {preContent?.unit}
                  {preContent?.hasInfinity
                    && <Checkbox className='select-none' disabled={hasInfinity() > -1 && name !== hasInfinity()} checked={currentRule?.infinity} onClick={() => checkItem(name)}>无上限</Checkbox>}
                  {afterHalfContent?.label}
                  <Form.Item
                    {...rest}
                    name={[name, 'reward']}
                    fieldKey={[fieldKey, 'reward']}
                    rules={[{
                      required: true,
                      validator: afterHalfContent?.validator ? afterHalfContent?.validator : (_: never, value: any) => value ? Promise.resolve() : Promise.reject(new Error(afterHalfContent?.placeholder))
                    }]}
                  >
                    <InputNumber min={0} placeholder={afterHalfContent?.placeholder} />
                  </Form.Item>{afterHalfContent?.unit}
                  { fields.length > 1 && <MinusCircleOutlined onClick={() => remove(name)} />}
                </Space>
              )
            })}
            <Form.Item style={{ display: 'none' }}>
              <Button type="dashed" ref={addBtn} onClick={() => add()} block icon={<PlusOutlined />} />
            </Form.Item>
          </>
        )
      }}
    </Form.List >
  ), [form, preContent, afterHalfContent, checkItem, hasInfinity]);

  const addition = useCallback(() => {
    addBtn?.current?.click();
  }, []);

  return (
    <Form name="dynamic_rules_form" form={form} autoComplete="off">
      <Button type='primary' onClick={addition}>新增</Button>
      <Button type='primary' onClick={onFinish}>submit</Button>
      {DynamicFormList}
    </Form >
  )
}
export type { Rules };
export default BaseDynamicRule;
